
import { isEmpty, } from 'lodash-es';

/**
 * 将扁平数据转换成树形数据
 * @param data
 * @param config
 * @returns {unknown[]}
 */
export function convertToTree(data, config = { id: 'deptId', parentId: 'parentId', }) {
  const tree = {};
  const map = {};
  const arr = JSON.parse(JSON.stringify(data));
  arr.forEach((item) => {
    const id = item[config.id];
    const pid = item[config.parentId];
    map[id] = item;
    if (pid !== 0 && pid) {
      const parent = map[pid];
      if (parent) {
        parent['children'] = parent.children || [];
        parent.children.push(item);
      }
    } else {
      tree[id] = item;
    }
  });
  if (isEmpty(tree)) {
    return Object.values(map);
  }
  return Object.values(tree);
}

